package com.xxx.springboot.controller;

import java.util.Random;

import javax.validation.constraints.Min;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.springboot.annotation.AccessAuth;
import com.xxx.springboot.pojo.Result;
import com.xxx.springboot.pojo.entity.User;
import com.xxx.springboot.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * user Controller
 */
@Api(description = "用户操作接口")
@Controller
@RequestMapping(value = "/user", produces = "application/json;charset=utf-8")
public class UserController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;
	
    /**
     * 分页查询列表
     * @return
     */
    @AccessAuth(anyPermissionCodes = "pageList")
    @GetMapping("/pageList")
    @ResponseBody
    public String pageList(@RequestParam(defaultValue = "1") @Min(1) Integer pageNo,
                           @RequestParam(defaultValue = "10") @Min(1) Integer pageSize,
                           String userName) {
    	logger.info("enter method pageList(). userName:{}", userName);
        try {
        	LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        	if(!StringUtils.isEmpty(userName)) {
        		queryWrapper.likeRight(User::getUserName, userName);
        	}
        	IPage<User> page = new Page<>(pageNo, pageSize);
        	IPage<User> pageList = userService.page(page, queryWrapper);
            return Result.ok(pageList);
        } catch (Exception e) {
        	logger.error("pageList发生异常：{}", e);
            return Result.fail("发生异常");
        }
    }
    
    /**
     * 根据id查询
     */
    @AccessAuth(anyPermissionCodes = "getById")
    @GetMapping("/getById")
    @ResponseBody
    public User getById(Integer id) {
    	logger.info("enter method getById(). id:{}", id);
        try {
        	User user = userService.getById(id);
            return user;
        } catch (Exception e) {
        	logger.error("getById发生异常：{}", e);
            return null;
        }
    }
    
    /**
     * 根据name查询
     */
    @AccessAuth(anyPermissionCodes = "getByName")
    @GetMapping("/getByName")
    @ResponseBody
    public String getByName(String username) {
    	logger.info("enter method getByName(). username:{}", username);
        try {
        	User user = userService.getByName(username);
            return Result.ok(user);
        } catch (Exception e) {
        	logger.error("getByName发生异常：{}", e);
            return Result.fail("发生异常");
        }
    }
    
    /**
     * 保存
     */
    @AccessAuth(anyPermissionCodes = "save")
    @PostMapping("/save")
    @ResponseBody
    public String save(@RequestBody @Validated User entity) {
    	logger.info("enter method save(). entity:{}", entity.toString());
        try {
        	boolean result = userService.save(entity);
            return Result.ok(result);
        } catch (Exception e) {
        	logger.error("save发生异常：{}", e);
            return Result.fail("发生异常");
        }
    }

    /**
     * 修改
     */
    @AccessAuth(anyPermissionCodes = "update")
    @PostMapping("/update")
    @ResponseBody
    public String update(@RequestBody @Validated User entity) {
    	logger.info("enter method update(). entity:{}", entity.toString());
        try {
        	boolean result = userService.updateById(entity);
            return Result.ok(result);
        } catch (Exception e) {
        	logger.error("update发生异常：{}", e);
            return Result.fail("发生异常");
        }
    }
    
    /**
     * 删除
     */
    @AccessAuth(anyPermissionCodes = "delete")
    @PostMapping("/delete")
    @ResponseBody
    public String delete(Integer id) {
    	logger.info("enter method delete(). id:{}", id);
        try {
        	boolean result = userService.removeById(id);
            return Result.ok(result);
        } catch (Exception e) {
        	logger.error("delete发生异常：{}", e);
            return Result.fail("发生异常");
        }
    }
    
    /**
     * Swagger
     * @param telphone
     * @return
     */
    @ApiOperation(value = "获取otp", notes="通过手机号获取OTP验证码")
    @ApiImplicitParam(name = "telephone", value = "电话号码", paramType = "query", required = true, dataType = "Integer")
    @RequestMapping(value = "getotp", method=RequestMethod.GET)
    @ResponseBody
    public String getOtp(@RequestParam(name = "telephone") String telphone) {
        //需要按照一定的规则生成OTP验证码
        Random random = new Random();
        int randomInt = random.nextInt(99999);
        randomInt += 10000;
        String otpCode = String.valueOf(randomInt);

        //将OTP验证码通过短信通道发送给用户，省略
        System.out.println("telphone = " + telphone + "& otpCode = " + otpCode);
        return otpCode;
    }
    
}
